package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiexu
 * @create 2022-06-08 17:57
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 不拦截所有的静态资源
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 授权
        http.authorizeRequests().antMatchers("/user/setting", "/user/upload", "/discuss/add", "/comment/add/**", "/letter/**", "/notice/**", "/like", "/follow", "/unfollow").hasAnyAuthority(AUTHORITY_USER, AUTHORITY_ADMIN, AUTHORITY_MODERATOR)
                // 版主可以对帖子进行置顶、加精
                .antMatchers("/discuss/top", "/discuss/wonderful", "/discuss/delete").hasAnyAuthority(AUTHORITY_MODERATOR)
                // 管理员可以对帖子进行删除，并且管理员可以对网站进行统计
                .antMatchers("/discuss/delete", "/data/**").hasAnyAuthority(AUTHORITY_ADMIN)
                // 除了上面这些请求需要特殊权限外，其他请求都通通允许
                .anyRequest().permitAll()
                // 关闭CSRF检查
                .and().csrf().disable();

        // 权限不够时的处理
        http.exceptionHandling()
                // 没有登录时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        // 判断当前请求是同步还是异步
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHTTPRequest".equals(xRequestedWith)) { // 异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登录哦！"));
                        } else { // 同步请求
                            // 重定向到登录页面
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                // 权限不足时的处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        // 判断当前请求是同步还是异步
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHTTPRequest".equals(xRequestedWith)) { // 异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限哦！"));
                        } else { // 同步请求
                            // 重定向到权限不足的页面
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // Security底层默认会拦截"/logout"请求，进行退出处理
        // 覆盖默认的逻辑，才能执行我们自己的退出代码
        // 善意的欺骗，拦截一个不存在的退出请求，这样才能让程序执行我们自己的退出代码
        http.logout().logoutUrl("/securitylogout");
    }
}
